<script setup lang="ts">
import {
  addAddressAPI,
  getAddressInfoAPI,
  updateAddressAPI,
} from '@/services/address'
import { ref } from 'vue'
//@ts-ignore
import { throttle } from 'lodash'
import { onLoad } from '@dcloudio/uni-app'
import type { AddressItem } from '@/types/global'
import type { UniFormsRules } from '@uni-helper/uni-ui-types'

// 表单数据 要使用v-model收集数据因此需要进行初始化数据
const form = ref<AddressItem>({
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
})
// 获取页面路由参数(有id为修改无id为新增)
const query = defineProps<{
  id?: string
}>()
// 动态设置标题
uni.setNavigationBarTitle({
  title: query.id ? '修改收货地址' : '新增收货地址',
})
// 获取地址详情数据
const getAddressInfo = async () => {
  // 如果路由参数中有id，获取地址详情数据
  if (query.id) {
    const result = await getAddressInfoAPI(query.id!)
    // 将获取的数据存储到form中
    form.value = result.result
  }
}
// 地址表单实例对象
const formRef = ref<UniHelper.UniFormsInstance>()
// picker选择器选择地址后的回调
const onReginSelect: UniHelper.RegionPickerOnChange = (event) => {
  // 获取选择的地址编码和地址
  const { code, value } = event.detail
  // 收集参数
  form.value.provinceCode = code![0]
  form.value.cityCode = code![1]
  form.value.countyCode = code![2]
  // 数据回显
  form.value.fullLocation = value.join(' ')
}
// switch选择器改变时的回调
const onSwitchChange: UniHelper.SwitchOnChange = (event) => {
  // 更新默认选择的值
  form.value.isDefault = event.detail.value ? 1 : 0
}
// 定义表单校验规则
const rules: UniFormsRules = {
  // 收货人
  receiver: {
    rules: [
      {
        required: true,
        errorMessage: '请填写收货人姓名',
      },
    ],
  },
  // 联系方式
  contact: {
    rules: [
      {
        required: true,
        errorMessage: '请填写手机号码',
      },
      {
        pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
        errorMessage: '请填写正确的手机号码',
      },
    ],
  },
  // 省市区
  fullLocation: {
    rules: [
      {
        required: true,
        errorMessage: '请选择所在地区',
      },
    ],
  },
  // 详细地址
  address: {
    rules: [
      {
        required: true,
        errorMessage: '请填写详细地址',
      },
    ],
  },
}
// 点击保存按钮的事件回调(关键按钮--节流)
const onSave = throttle(async () => {
  // 表单校验
  try {
    await formRef.value?.validate?.()
    // 判断是修改还是新增(form中是否有id)
    form.value.id
      ? await updateAddressAPI(form.value)
      : await addAddressAPI(form.value)
    // 提示
    await uni.showToast({
      title: form.value.id ? '更新成功' : '新增成功',
      icon: 'success',
    })
    // 返回上一页(提示延迟0.5s)
    setTimeout(() => {
      uni.navigateBack()
    }, 500)
  } catch (error) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'error',
      mask: true,
    })
  }
}, 1500)

onLoad(() => {
  //获取地址详情数据
  getAddressInfo()
})
</script>

<template>
  <view class="content">
    <uni-forms
      ref="formRef"
      :modelValue="form"
      :rules="rules"
      border
      :label-width="110"
    >
      <!-- 表单内容 -->
      <uni-forms-item name="receiver" required label="收货人">
        <input
          class="input"
          placeholder="请填写收货人姓名"
          v-model="form.receiver"
        />
      </uni-forms-item>
      <uni-forms-item name="contact" required label="手机号码">
        <input
          class="input"
          placeholder="请填写收货人手机号码"
          v-model="form.contact"
        />
      </uni-forms-item>
      <uni-forms-item name="fullLocation" required label="所在地区">
        <picker
          class="picker"
          mode="region"
          @change="onReginSelect"
          :value="form.fullLocation!.split(' ')"
        >
          <view v-if="form.fullLocation" class="picker-content">{{
            form.fullLocation
          }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
        <!-- <view class="location" @tap="onLocation">
          <text>定位</text>
        </view> -->
      </uni-forms-item>
      <uni-forms-item name="address" required label="详细地址">
        <input
          class="input"
          placeholder="街道、楼牌号等信息"
          v-model="form.address"
        />
      </uni-forms-item>
      <uni-forms-item label="设为默认地址">
        <switch
          class="switch"
          color="#27ba9b"
          style="transform: scale(0.7)"
          @change="onSwitchChange"
          :checked="form.isDefault === 1"
        />
      </uni-forms-item>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @click="onSave">保存并使用</button>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  .uni-forms-item {
    height: 120rpx;
    .uni-forms-item__content {
      padding-top: 16rpx;
      .uni-forms-item__error {
        margin-top: -10rpx;
        height: 25rpx;
        font-size: 25rpx;
      }
    }
    .uni-forms-item__label,
    .input {
      font-size: 28rpx;
    }
    .placeholder {
      margin-bottom: 10rpx;
      color: #808080;
      font-size: 28rpx;
    }
    .picker {
      .picker-content {
        font-size: 28rpx;
      }
    }
    &:last-child {
      height: 100rpx;
      display: flex;
      align-items: center;
      .switch {
        margin-left: 310rpx;
      }
    }
  }
  /*   .location {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80rpx;
    margin: -24rpx -12rpx -24rpx 0rpx;

    text {
      font-size: 25rpx;
      color: #777;
      margin-left: 6rpx;
    }
  } */
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>
